package com.cn.task;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletContext;

import com.cn.app.AppContext;
import com.cn.bean.SimpleMap;
import com.cn.xc.utils.DateUtil;
import com.cn.xc.utils.StringUtil;

/**
 * FUN: 处理文件名，文件路径
 * 
 * @author sushy
 * @date 2016-3-23
 */
public class CtgFileService {

	private static String baseDirPath = "/curfile/files";// 存放文件绝对目录

	/**
	 * //# 当前目录为：crmtask\ftpfile ,subPath非空，就在下面增加 subPath子目录，
	 * cityId非空，增加，cityId子目录
	 * 
	 * @param subPath
	 * @return
	 */
	public static String genFilePath(String subPath) {

		if (StringUtil.isEmpty(baseDirPath)) {
			StringBuffer basePath = new StringBuffer();
			ServletContext sc = AppContext.getServletContext();
			if (sc != null) {
				basePath.append(sc.getRealPath(""));
				basePath.append("/");
			} else {
				ClassLoader cl = Thread.currentThread().getContextClassLoader();
				URL url = cl.getResource("/");
				if (url == null) {
					url = cl.getResource("");
				}
				String fp = url.getPath().replaceAll("\\\\", "/");
				basePath.append(fp.replaceAll("/WEB-INF/classes", ""));
			}
			basePath.append("ftpfile/");
			baseDirPath = basePath.toString().replaceAll("\\\\", "/");
		}

		StringBuilder filePath = new StringBuilder(baseDirPath);
		if (StringUtil.isNotEmpty(subPath)) {
			filePath.append(subPath).append("/");
		}
		String filePathStr = filePath.toString();

		// 确保文件夹存在
		File file = new File(filePathStr);
		if (file.exists()) {
			if (!file.isDirectory()) {
				file.delete();// 删除文件
				file.mkdir();// 创建目录
			}
		} else {
			file.mkdirs();// 创建目录
		}

		return filePathStr;
	}

	/**
	 * //# 创建文件
	 * 
	 * @param file
	 */
	public static void createNewFile(File file) {
		createNewFile(file, true);
	}

	/**
	 * 创建新文件
	 * 
	 * @param file
	 */
	public static void createNewFile(File file, boolean isForce) {
		if (file.exists()) {
			if (isForce) {
				file.delete();
			} else {
				return;
			}
		}
		try {
			file.createNewFile();
		} catch (IOException e) {
			throw new RuntimeException("---新建文件失败!---" + file, e);
		}
	}

	/**
	 * @param filePath
	 * @param fileName
	 * @param cityFlag
	 * @return Description ：
	 *         根据path和filename生成新文件，如果cityFlag文真，在path加一个cityId的子文件夹，文件放下面
	 * 
	 */
	public static File getFile(String filePath, String fileName) {
		StringBuilder desPath = new StringBuilder();

		if (StringUtil.isEmpty(filePath)) {
			StringBuffer basePath = new StringBuffer();
			ServletContext sc = AppContext.getServletContext();
			if (sc != null) {
				basePath.append(sc.getRealPath(""));
				basePath.append("/");
			} else {
				ClassLoader cl = Thread.currentThread().getContextClassLoader();
				URL url = cl.getResource("/");
				if (url == null) {
					url = cl.getResource("");
				}
				String fp = url.getPath().replaceAll("\\\\", "/");
				basePath.append(fp.replaceAll("/WEB-INF/classes", ""));
			}
			basePath.append("ftpfile/");
			filePath = basePath.toString().replaceAll("\\\\", "/");
		}

		desPath = new StringBuilder(filePath);
		String finPath = desPath.toString();

		// 确保文件夹存在
		File file = new File(finPath);
		if (file.exists()) {
			if (!file.isDirectory()) {
				file.delete();// 删除文件
				file.mkdirs();// 创建目录
			}
		} else {
			file.mkdirs();// 创建目录
		}

		return new File(finPath + fileName);
	}

	/**
	 * //# 合并文件到流
	 * 
	 * @param fromFile
	 *            文件
	 * @param fos
	 *            输出流
	 */
	public static void appendFile2Des(String fromFile, FileOutputStream fos) {

		BufferedInputStream in = null;
		BufferedOutputStream out = null;
		try {
			if (StringUtil.isEmpty(fromFile)) {
				return;
			}

			File from = new File(fromFile);
			if (!from.exists()) {
				return;
			}

			if (fos == null) {
				return;

			}
			in = new BufferedInputStream(new FileInputStream(from));
			out = new BufferedOutputStream(fos);
			int b = 0;
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
			out.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}

	}

	/**
	 * //# 获取指定格式的时间
	 * 
	 * @param date
	 *            时间
	 * @param format
	 *            格式
	 * @param genDateFormat
	 *            配置串
	 * @return
	 */
	public static String getDateFormat(Date date, String format, String genDateFormat) {

		if (date == null) {
			date = new Date();
		}

		if (StringUtil.isEmpty(format)) {
			format = "yyyyMMdd";
		}

		String dateFormat = "";

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);

		if (StringUtil.isNotEmpty(genDateFormat)) {
			String[] genCons = StringUtil.splitTokens(genDateFormat, "%");

			if ("date".equals(genCons[0])) {
				if (genCons.length > 1) {
					String suffix = genCons[1];
					long dateSuffix = Long.valueOf(suffix);
					if (dateSuffix > 0 && dateSuffix < 10) {
						while (calendar.get(Calendar.DAY_OF_MONTH) % 10 != dateSuffix) {
							calendar.add(Calendar.DAY_OF_MONTH, -1);
						}
					}
				}
			} else if ("day".equals(genCons[0])) {
				if (genCons.length > 1) {
					String suffix = genCons[1];
					long daySuffix = Long.valueOf(suffix);
					if (daySuffix > 0 && daySuffix < 8) {
						while (calendar.get(Calendar.DAY_OF_WEEK) % daySuffix > 0) {
							calendar.add(Calendar.DAY_OF_MONTH, -1);
						}
					}
				}
			} else if ("yesterday".equals(genDateFormat)) {
				calendar.add(Calendar.DAY_OF_MONTH, -1);
			}
		}

		dateFormat = DateUtil.date2Str(calendar.getTime(), format);

		return dateFormat;

	}

	/**
	 * //# 根据配置串获取文件名
	 * 
	 * @param fileNameCons
	 *            配置串--tb_ic_task_conf
	 * @param param
	 *            参数
	 * @param cityFlag
	 *            是否添加本地网作为路径
	 * @return
	 */
	public static String getFileName(String fileNameCons, SimpleMap param) {

		if (StringUtil.isEmpty(fileNameCons)) {
			fileNameCons = "dateFormat~yyyyMMdd";
		}
		String[] fileCons = StringUtil.splitTokens(fileNameCons, ",");
		String fileName = "";
		String replaceName = "";
		StringBuffer sb = new StringBuffer();
		for (String cons : fileCons) {
			if (cons.length() > 11 && "dateFormat".equals(cons.substring(0, 10))) {
				String[] dateCons = StringUtil.splitTokens(cons, "~");
				String format = "";
				String genDateFormat = "";
				if (dateCons.length > 1) {
					format = dateCons[1];
				}
				if (dateCons.length > 2) {
					genDateFormat = dateCons[2];
				}
				String dateStr = getDateFormat(new Date(), format, genDateFormat);
				sb.append(dateStr);

			} else if (cons.length() > 5 && "param".equals(cons.substring(0, 5))) {
				String[] dataCons = StringUtil.splitTokens(cons, "~");
				if (dataCons.length > 1) {
					sb.append(param.get(dataCons[1]));
				}
			} else if (cons.length() >= 7 && "fileSeq".equals(cons.substring(0, 7))) {
				if ("yes".equals(param.getString("needFileSeq"))) {
					String seqFormat = "";
					String[] dataCons = StringUtil.splitTokens(cons, "~");
					if (dataCons.length > 1) {
						seqFormat = dataCons[1];
					}
					if (StringUtil.isNotEmpty(seqFormat)) {
						AtomicIntSeq seq = (AtomicIntSeq) param.get("fileSeq");
						String strForamt = "%1$" + seqFormat + "d";
						String finalSeq = String.format(strForamt, seq.getSeq());
						if (StringUtil.isNotEmpty(finalSeq)) {
							sb.append(finalSeq);
						}
					}
				} else {
					continue;
				}
			} else if (cons.length() > 13 && "variableName".equalsIgnoreCase(cons.substring(0, 12))) {
				continue;
			} else if (cons.length() > 11 && "mustUpload".equalsIgnoreCase(cons.substring(0, 10))) {
				continue;
			} else {
				sb.append(cons);
			}
		}
		fileName = sb.toString();
		replaceName = param.getString("replaceName");
		if ("####".equals(fileName.substring(10, 14))) {
			fileName = fileName.replace("####", replaceName);
			System.out.println("---文件命名： replaceName ####->" + replaceName + "---fileName:" + fileName);
		} else {
			System.out.println("---文件命名： not need replaceName,---fileName:" + fileName);
		}

		return fileName;
	}

}
